-module(cloap_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).
-export([use_sso/0]).
-define(APP, cloap).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    Dispatch = cowboy_router:compile([
        {'_', [
               {"/", cowboy_static, {priv_file, ?APP, "index.html"}},
               {"/static/[...]", cowboy_static, {priv_dir, ?APP, "static"}},
               {"/websocket", cloap_handler, []},
               {"/cloap/app/:appid/partial/[...]", cloap_module_handler, []},
               {"/cloap/app/:appid/js/[...]", cloap_module_handler, []},
               {"/cloap/app/:appid/css/[...]", cloap_module_handler, []},
               {"/cloap/app/:appid/[...]", cloap_esb, []},
               {"/cloap/admin/[...]", cloap_rest, []}
        ]}
    ]),

    cowboy:start_http(cloap_portal_listener, 100,
        [{port, application:get_env(?APP, port, 80)}],
        [
         {env, [{dispatch, Dispatch}]},
         {middlewares, middlewares()}
        ]
    ),


    DispatchEsb = cowboy_router:compile(
                    [
                     {'_',
                      [
                       {"/", cowboy_static, {priv_file, ?APP, "index.html"}},
                       {"/role/:dim/[:id]",  role_handler, []},
                       {"/role/:dim/:id/[:action]", role_handler, []},
                       {"/cloap/app/:appid/[...]", cloap_esb, []},
                       {"/cloap/admin/[...]", cloap_rest, []}
                      ]
                     }
                    ]),

    cowboy:start_http(cloap_esb_listener, 100,
        [{port, application:get_env(?APP, esb_port, 8080)}],
        [
         {env, [{dispatch, DispatchEsb}]}
        ]
    ),

    Result = cloap_sup:start_link(),
    cloap_event_logger:add_handler(),
    % cloap_event_action_counter:add_handler(),
    Result.

stop(_State) ->
    ok.



middlewares() ->
    case use_sso() of
        false ->
            [cowboy_router, cowboy_handler];
        true ->
            [cowboy_cas_client, cowboy_router, cowboy_handler]
    end.


use_sso() ->
    application:get_env(?APP, sso, false).




